import 'dart:convert';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/common/utils/extension_util.dart';
import 'package:oramemo/core/controllers/record_controller.dart';
import 'package:oramemo/entity/voice_record_transliterate_entity.dart';
import 'package:oramemo/widgets/audio/audio_player_controller.dart';
import 'package:oramemo/common/langs/text_key.dart';

import 'transcription_details_state.dart';

class TranscriptionDetailsLogic extends GetxController {
  final Transcription_detailsState state = Transcription_detailsState();
  final RecordController controller = Get.find<RecordController>();
  VoiceRecordTransliterateEntity transliterateEntity =
      VoiceRecordTransliterateEntity();
  AudioPlayerController audioPlayerController = AudioPlayerController();
  bool isPlayer = false;
  VoiceRecordTransliterateSegments? selectSegment;
  final ScrollController scrollController = ScrollController();

  var isLiked = false;

  @override
  void onInit() async {
    await _reqestData();
    audioPlayerController.addListener(audioUpdate);
    super.onInit();
  }

  void audioUpdate() {
    final position = audioPlayerController.position;

    for (final VoiceRecordTransliterateSegments data
        in transliterateEntity.segments ?? []) {
      final start = (data.start.toDouble() ?? 0) * 1000;
      final end = (data.end.toDouble() ?? 0) * 1000;
      final inSeconds = position.inMilliseconds;
      if (inSeconds > start && inSeconds < end) {
        selectSegment = data;
        update();
        return;
      }
    }
  }

  void setForward(VoiceRecordTransliterateSegments data) {
    selectSegment = data;
    if (data.start?.isNotEmpty == true) {
      final start = (data.start.toDouble() ?? 0) * 1000;

      audioPlayerController.setForward(Duration(milliseconds: start.toInt()));
    }
    update();
  }

  // 修改滚动方法
  void scrollToSegment(VoiceRecordTransliterateSegments segment) {
    final index = transliterateEntity.segments?.indexOf(segment) ?? -1;
    if (index == -1) return;

    final itemHeight = 60.0; // 预估每个item的高度
    final viewportHeight = scrollController.position.viewportDimension;
    final maxScroll = scrollController.position.maxScrollExtent;

    // 计算目标滚动位置（使item位于中间）
    double targetScroll =
        (index * itemHeight) - (viewportHeight / 2) + (itemHeight / 2);
    targetScroll = targetScroll.clamp(0.0, maxScroll);

    // 执行滚动动画
    scrollController.animateTo(
      targetScroll,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  @override
  void onClose() {
    super.onClose();
    audioPlayerController.removeListener(audioUpdate);
    scrollController.dispose();
  }

  Future<void> _reqestData() async {
    int? id = Get.arguments as int?;
    await controller.getVoiceRecordDetail(id?.toString() ?? '');
    String? jsonString1 = controller.selectedVoiceRecord?.voiceTransliterate;
    jsonString1 = jsonString1?.replaceAll("'", '"');
    if (jsonString1 != null) {
      Map<String, dynamic> json = jsonDecode(jsonString1);
      transliterateEntity = VoiceRecordTransliterateEntity.fromJson(json);
      update();
    }
    final voicePath = controller.selectedVoiceRecord?.voicePath;
    if (voicePath?.isNotEmpty == true) {
      DefaultCacheManager().downloadFile(voicePath.toFullUrl());
    }
  }

  void toggleLike() {
    isLiked = !isLiked;
    update();
  }

  // 存储书签的Set
  final Set<String> _bookmarks = {};

  // 获取段落的书签状态
  bool isBookmarked(String segmentId) => _bookmarks.contains(segmentId);

  // 切换当前选中段落的书签状态
  void toggleBookmark() {
    if (selectSegment == null) {
      Toast.show(TextKey.transcriptionUploadError.tr);
      return;
    }

    String? segmentId = selectSegment!.id?.toString();
    if (segmentId == null) return;

    if (isBookmarked(segmentId)) {
      _bookmarks.remove(segmentId);
    } else {
      _bookmarks.add(segmentId);
    }

    update();
  }

  // 获取当前选中段落的书签状态
  bool get isCurrentBookmarked {
    if (selectSegment == null) return false;
    return isBookmarked(selectSegment!.id?.toString() ?? '');
  }

  // 获取所有书签段落（按时间排序）
  List<VoiceRecordTransliterateSegments> getBookmarkedSegments() {
    final bookmarked = transliterateEntity.segments
            ?.where((segment) => isBookmarked(segment.id.toString()))
            .toList() ??
        [];

    // 按时间排序
    bookmarked.sort((a, b) {
      final aTime = (a.start?.toDouble() ?? 0);
      final bTime = (b.start?.toDouble() ?? 0);
      return aTime.compareTo(bTime);
    });

    return bookmarked;
  }

  // 删除书签
  void removeBookmark(String segmentId) {
    _bookmarks.remove(segmentId);
    update();
  }
}
